<template>
	<view>
		<view class="list">
			<picker class="picker" mode="multiSelector" :range="region" range-key="value" :value="regionIndex" @change="pickerChange" @columnchange="pickerColumnchange">
				<view class="pbox" :class="{ pbox_hover: regionStr != '请选择省市区' }">
					<view class="texts">{{ regionStr }}</view>
				</view>
			</picker>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		citylist: {
			type: Array,
			default() {
				return [];
			}
		}
	},
	data() {
		return {
			oldRegion: [],
			region: [[], [], []],
			regionIndex: [0, 0, 0],
			regionStr: '请选择省市区',
			previnceId: '北京市',
			cityId: '北京市',
			countyId: '东城区',
			isDataLoaded: false // 添加数据加载状态
		};
	},
	watch: {
		citylist: {
			handler(newVal) {
				// 只有数据加载完成后才初始化
				if (this.isDataLoaded) {
					this.initRegionData(newVal);
				}
			},
			deep: true,
			immediate: true
		}
	},
	created() {
		this.loadRegionData();
	},
	methods: {
		// 加载地区数据
		loadRegionData() {
			uni.request({
				url: 'https://www.daolangtongge.com/read-book-api/profile/mini_app/json/ChinaCitys.json',
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 200) {
						this.oldRegion = res.data;
						this.isDataLoaded = true;
						console.log('地区数据加载成功:', this.oldRegion);
						
						// 数据加载完成后初始化
						this.initRegionData(this.citylist);
					} else {
						console.error('请求失败:', res.statusCode);
						this.handleError('请求失败');
					}
				},
				fail: (err) => {
					console.error('网络错误:', err);
					this.handleError('网络错误');
				}
			});
		},
		
		// 初始化地区数据
		initRegionData(newVal) {
			if (!this.isDataLoaded) {
				console.log('数据尚未加载完成，等待加载...');
				return;
			}
			
			console.log('开始初始化地区数据:', newVal);
			
			// 重置地区数据
			this.region = [[], [], []];
			
			if (newVal && newVal.length === 3) {
				this.previnceId = newVal[0];
				this.cityId = newVal[1];
				this.countyId = newVal[2];
				this.regionStr = newVal.join('/');
			} else {
				this.regionStr = '请选择省市区';
			}
			
			// 处理省份数据
			let provinceArr = [];
			let cityArr = [];
			let foundProvince = false;
			let foundCity = false;
			
			// 第一列：省份
			this.oldRegion.forEach((item, index) => {
				this.region[0].push({
					value: item.value,
					code: item.code
				});
				
				// 查找默认选中的省份
				if (this.previnceId === item.value) {
					provinceArr = item.children || [];
					this.regionIndex[0] = index;
					foundProvince = true;
				}
			});
			
			// 如果没有找到匹配的省份，使用第一个
			if (!foundProvince && this.oldRegion.length > 0) {
				provinceArr = this.oldRegion[0].children || [];
				this.regionIndex[0] = 0;
			}
			
			// 第二列：城市
			provinceArr.forEach((item, index) => {
				this.region[1].push({
					value: item.value,
					code: item.code
				});
				
				// 查找默认选中的城市
				if (this.cityId === item.value) {
					cityArr = item.children || [];
					this.regionIndex[1] = index;
					foundCity = true;
				}
			});
			
			// 如果没有找到匹配的城市，使用第一个
			if (!foundCity && provinceArr.length > 0) {
				cityArr = provinceArr[0].children || [];
				this.regionIndex[1] = 0;
			}
			
			// 第三列：区县
			cityArr.forEach((item, index) => {
				this.region[2].push({
					value: item.value,
					code: item.code
				});
				
				// 查找默认选中的区县
				if (this.countyId === item.value) {
					this.regionIndex[2] = index;
				}
			});
			
			console.log('初始化完成:', this.region);
		},
		
		pickerChange(e) {
			console.log('选择改变:', e);
			const [provinceIdx, cityIdx, countyIdx] = e.detail.value;
			
			if (this.region[0][provinceIdx] && this.region[1][cityIdx] && this.region[2][countyIdx]) {
				this.regionIndex = e.detail.value;
				this.regionStr = `${this.region[0][provinceIdx].value}/${this.region[1][cityIdx].value}/${this.region[2][countyIdx].value}`;
				this.$emit('regionStr', this.regionStr);
			}
		},
		
		pickerColumnchange(e) {
			console.log('列改变:', e);
			const column = e.detail.column;
			const value = e.detail.value;
			
			if (column === 0) {
				// 省份改变
				this.handleProvinceChange(value);
			} else if (column === 1) {
				// 城市改变
				this.handleCityChange(value);
			}
		},
		
		handleProvinceChange(provinceIndex) {
			// 更新城市列表
			const province = this.oldRegion[provinceIndex];
			if (!province || !province.children) return;
			
			const cities = province.children.map(item => ({
				value: item.value,
				code: item.code
			}));
			
			// 更新区县列表（默认第一个城市）
			const firstCity = province.children[0];
			const counties = firstCity && firstCity.children ? 
				firstCity.children.map(item => ({
					value: item.value,
					code: item.code
				})) : [];
			
			this.regionIndex = [provinceIndex, 0, 0];
			this.region[1] = cities;
			this.region[2] = counties;
			
			// 强制更新视图
			this.$forceUpdate();
		},
		
		handleCityChange(cityIndex) {
			const provinceIndex = this.regionIndex[0];
			const province = this.oldRegion[provinceIndex];
			if (!province || !province.children) return;
			
			const city = province.children[cityIndex];
			const counties = city && city.children ? 
				city.children.map(item => ({
					value: item.value,
					code: item.code
				})) : [];
			
			this.regionIndex[1] = cityIndex;
			this.regionIndex[2] = 0;
			this.region[2] = counties;
			
			// 强制更新视图
			this.$forceUpdate();
		},
		
		handleError(message) {
			uni.showToast({
				title: message,
				icon: 'none'
			});
		}
	}
};
</script>

<style lang="scss">
.ulist {
	display: flex;
	padding: 0rpx 0rpx;
	height: 21px;
	align-items: center;
}
.picker {
	flex: 1;
	.pbox {
		display: flex;
		align-items: center;
		color: #dadada;
		box-sizing: border-box;
		border-radius: 20rpx;
		font-family: PingFang SC, PingFang SC;
		font-size: 28rpx;
	}
	.pbox_hover {
		color: #75613e;
	}
	.texts {
		text-align: left;
	}
}
</style>
